package com.sangananitsolution.fragments;

import java.util.ArrayList;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import Utiliypackage.UilityClassFroTime;
import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.sangananitsolution.gogoproject.R;

public class MapFragmants extends Fragment implements OnMapClickListener {

	int count = 0;
	double latitutevalue, longitutevalue;
	ArrayList<String> description = new ArrayList<String>();
	ArrayList<String> suburb = new ArrayList<String>();
	ArrayList<String> startdate = new ArrayList<String>();
	ArrayList<String> startime = new ArrayList<String>();
	ArrayList<String> finishtime = new ArrayList<String>();
	ArrayList<String> productImagesarray = new ArrayList<String>();
	ArrayList<String> productID = new ArrayList<String>();
	ArrayList<String> garageSaleTitle = new ArrayList<String>();
	ArrayList<String> oneOrTwoDaySale = new ArrayList<String>();
	ArrayList<String> unitStreeNo = new ArrayList<String>();
	ArrayList<String> streeName = new ArrayList<String>();
	ArrayList<String> city = new ArrayList<String>();
	ArrayList<String> state = new ArrayList<String>();
	ArrayList<String> postCodearray = new ArrayList<String>();
	ArrayList<String> earlyBirdMessage = new ArrayList<String>();
	ArrayList<String> badWeatherMessage = new ArrayList<String>();
	ArrayList<String> goodsTypearray = new ArrayList<String>();
	ArrayList<String> currentUser = new ArrayList<String>();
	ArrayList<String> longitude = new ArrayList<String>();
	ArrayList<String> latitude = new ArrayList<String>();
	// Google Map
	private GoogleMap googleMap;

	public MapFragmants(double longitutevalues, double latitutevalues) {
		this.latitutevalue = latitutevalues;
		this.longitutevalue = longitutevalues;
	}

	@Override
	public void onAttach(Activity activity) {

		new MysearchLocationnearByAPi().execute();

		try {
			// Loading map
			initilizeMap();

			// Changing map type
			googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

			// Showing / hiding your current location
			googleMap.setMyLocationEnabled(true);

			// Enable / Disable zooming controls
			googleMap.getUiSettings().setZoomControlsEnabled(false);

			// Enable / Disable my location button
			googleMap.getUiSettings().setMyLocationButtonEnabled(true);

			// Enable / Disable Compass icon
			googleMap.getUiSettings().setCompassEnabled(true);

			// Enable / Disable Rotate gesture
			googleMap.getUiSettings().setRotateGesturesEnabled(true);

			// Enable / Disable zooming functionality
			googleMap.getUiSettings().setZoomGesturesEnabled(true);

			double latitude = 28.5810916666;
			double longitude = 77.3245666;

			// lets place some 10 random markers
			for (int i = 0; i < 10; i++) {
				// random latitude and logitude
				double[] randomLocation = createRandLocation(28.5810916666,
						77.3245666);

				// Adding a marker
				MarkerOptions marker = new MarkerOptions().position(
						new LatLng(randomLocation[0], randomLocation[1]))
						.title("Hello Maps " + i);

				Log.e("Random", "> " + randomLocation[0] + ", "
						+ randomLocation[1]);

				// changing marker color
				if (i == 0)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
				if (i == 1)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
				if (i == 2)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
				if (i == 3)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
				if (i == 4)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
				if (i == 5)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
				if (i == 6)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_RED));
				if (i == 7)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
				if (i == 8)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
				if (i == 9)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));

				googleMap.addMarker(marker);

				// Move the camera to last position with a zoom level
				if (i == 9) {
					CameraPosition cameraPosition = new CameraPosition.Builder()
							.target(new LatLng(randomLocation[0],
									randomLocation[1])).zoom(15).build();

					googleMap.animateCamera(CameraUpdateFactory
							.newCameraPosition(cameraPosition));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		super.onAttach(activity);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.mapfragmnets, container, false);

		new MysearchLocationnearByAPi().execute();

		try {
			// Loading map
			initilizeMap();

			// Changing map type
			googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

			// Showing / hiding your current location
			googleMap.setMyLocationEnabled(true);

			// Enable / Disable zooming controls
			googleMap.getUiSettings().setZoomControlsEnabled(false);

			// Enable / Disable my location button
			googleMap.getUiSettings().setMyLocationButtonEnabled(true);

			// Enable / Disable Compass icon
			googleMap.getUiSettings().setCompassEnabled(true);

			// Enable / Disable Rotate gesture
			googleMap.getUiSettings().setRotateGesturesEnabled(true);

			// Enable / Disable zooming functionality
			googleMap.getUiSettings().setZoomGesturesEnabled(true);

			double latitude = 28.5810916666;
			double longitude = 77.3245666;

			// lets place some 10 random markers
			for (int i = 0; i < 10; i++) {
				// random latitude and logitude
				double[] randomLocation = createRandLocation(28.5810916666,
						77.3245666);

				// Adding a marker
				MarkerOptions marker = new MarkerOptions().position(
						new LatLng(randomLocation[0], randomLocation[1]))
						.title("Hello Maps " + i);

				Log.e("Random", "> " + randomLocation[0] + ", "
						+ randomLocation[1]);

				// changing marker color
				if (i == 0)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
				if (i == 1)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
				if (i == 2)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
				if (i == 3)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
				if (i == 4)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
				if (i == 5)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
				if (i == 6)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_RED));
				if (i == 7)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
				if (i == 8)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
				if (i == 9)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));

				googleMap.addMarker(marker);

				// Move the camera to last position with a zoom level
				if (i == 9) {
					CameraPosition cameraPosition = new CameraPosition.Builder()
							.target(new LatLng(randomLocation[0],
									randomLocation[1])).zoom(15).build();

					googleMap.animateCamera(CameraUpdateFactory
							.newCameraPosition(cameraPosition));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return view;

	}

	private class MysearchLocationnearByAPi extends
			AsyncTask<String, String, String> {

		private ProgressDialog pDialog;
		private final String URL = "http://garagesalesagogo.com.au/ProductService.asmx?op=SearchProducts1";
		private final String SOAP_ACTION = "http://tempuri.org/SearchProducts";
		private String TAG = "PGGURU";

		@Override
		protected String doInBackground(String... params) {
			Log.i(TAG, "I am in doInBackground");
			SoapObject searchProducts = null;
			SoapObject locationobj = null;
			SoapObject criteriaobj = null;

			searchProducts = new SoapObject("http://tempuri.org/",
					"SearchProducts");
			criteriaobj = new SoapObject("http://tempuri.org/", "criteria");

			locationobj = new SoapObject("http://tempuri.org/", "Location");
			locationobj
					.addProperty("Longitude", longitutevalue);
			locationobj.addProperty("Latitude", latitutevalue);
			locationobj.addProperty("Miles", "100");

			criteriaobj.addSoapObject(locationobj);
			searchProducts.addSoapObject(criteriaobj);

			// Create envelope
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.dotNet = true;
			// Set output SOAP object
			envelope.setOutputSoapObject(searchProducts);
			envelope.implicitTypes = true;
			// Create HTTP call object
			HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

			SoapObject searchProductsResponse = null;
			SoapObject searchProductsResult = null;
			SoapObject productDetails = null;
			SoapObject productImagesURL = null;

			SoapObject location = null;

			try {
				// Invole web service
				androidHttpTransport.call(SOAP_ACTION, envelope);
				// Get the response
				try {
					searchProductsResponse = (SoapObject) envelope.bodyIn;
				} catch (Exception exception) {
					Toast.makeText(getActivity(), "Tosat", 1000).show();
				}

				for (int i = 0; i < searchProductsResponse.getPropertyCount(); i++) {

					searchProductsResult = (SoapObject) searchProductsResponse
							.getProperty(i);

					for (int j = 0; j < searchProductsResult.getPropertyCount(); j++) {

						productDetails = (SoapObject) searchProductsResult
								.getProperty(j);
						
						
						
						
						String startdatevalue = (productDetails
								.getPropertyAsString("StartDate"));

						String starttimevalue = productDetails
								.getPropertyAsString("SaleStartTime");
						
						
						
						
						//UilityClassFroTime uilityClassFroTime=new UilityClassFroTime(startdatevalue, starttimevalue);
						String successvalue =	new UilityClassFroTime(startdatevalue, starttimevalue).testForeligbleEntry();
						
						
					/*	String successvalue = testForeligbleEntry(
								startdatevalue, starttimevalue);*/
						
						
						
						
						

								if (Integer.parseInt(successvalue) > 0) {
									description
											.add(productDetails
													.getPropertyAsString("Description"));
									suburb.add(productDetails
											.getPropertyAsString("Suburb"));

									try {
										productImagesURL = (SoapObject) productDetails
												.getProperty("ProductImagesURL");
										productImagesarray.add(productImagesURL
												.getPropertyAsString("string"));

									} catch (Exception e) {

										productImagesarray
												.add("~/ProductImages/2015215234459_323.png;");
										productImagesarray
												.add("~/ProductImages/2015215234459_323.png;");

									}

									startdate.add(productDetails
											.getPropertyAsString("StartDate"));
									startime.add(productDetails
											.getPropertyAsString("SaleStartTime"));
									finishtime
											.add(productDetails
													.getPropertyAsString("SaleFinishTime"));
									productID.add(productDetails
											.getPropertyAsString("ProductId"));
									garageSaleTitle
											.add(productDetails
													.getPropertyAsString("GarageSaleTitle"));
									oneOrTwoDaySale
											.add(productDetails
													.getPropertyAsString("OneOrTwoDaySale"));
									unitStreeNo
											.add(productDetails
													.getPropertyAsString("UnitStreeNo"));
									streeName.add(productDetails
											.getPropertyAsString("StreeName"));
									city.add(productDetails
											.getPropertyAsString("City"));
									state.add(productDetails
											.getPropertyAsString("State"));
									postCodearray.add(productDetails
											.getPropertyAsString("PostCode"));
									earlyBirdMessage
											.add(productDetails
													.getPropertyAsString("EarlyBirdMessage"));
									badWeatherMessage
											.add(productDetails
													.getPropertyAsString("BadWeatherMessage"));
									goodsTypearray.add(productDetails
											.getPropertyAsString("GoodsType"));

									currentUser
											.add(productDetails
													.getPropertyAsString("CurrentUser"));

									try {
										location = (SoapObject) productDetails
												.getProperty("Location");

										latitude.add(location
												.getPropertyAsString("Longitude"));
										longitude
												.add(location
														.getPropertyAsString("Latitude"));
									} catch (Exception e) {
										e.printStackTrace();
									}

								}

							}
						

					

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			Log.i(TAG, "I am in onPreExecute");
			// Showing progress dialog

			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Please wait for match List...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected void onPostExecute(String result) {
			if (pDialog.isShowing()) {

				pDialog.dismiss();

			}

			
			super.onPostExecute(result);

		}

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initilizeMap();
	}

	/**
	 * function to load map If map is not created it will create it for you
	 * */
	private void initilizeMap() {
		if (googleMap == null) {
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.map)).getMap();

			// check if map is created successfully or not
			if (googleMap == null) {
				Toast.makeText(getActivity(), "Sorry! unable to create maps",
						Toast.LENGTH_SHORT).show();
			}
		}
	}


	private double[] createRandLocation(double latitude, double longitude) {

		return new double[] { latitude + ((Math.random() - 0.5) / 500),
				longitude + ((Math.random() - 0.5) / 500),
				150 + ((Math.random() - 0.5) * 10) };
	}

	

	@Override
	public void onMapClick(LatLng arg0) {
		Toast.makeText(getActivity(), "helo from map", Toast.LENGTH_LONG).show();

	}
	/*public String testForeligbleEntry(String startdatevalue,
			String starttimevalue) {

		// finding the system current time and date of system
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
		Date date = new Date();
		String currentDate = sdf.format(date).toString();

		// getting minutes and hours from server
		String str = starttimevalue;
		int hours = 0, minutes = 0;
		DateFormat formatters = new SimpleDateFormat("h:mm a");
		Date dates;
		try {
			dates = formatters.parse(str);

			hours = dates.getHours();
			minutes = dates.getMinutes();
		} catch (ParseException e1) {

			e1.printStackTrace();
		}

		String salesStartDate = startdatevalue + " " + hours + ":"
				+ minutes;

		DateTimeZone timeZone = DateTimeZone.forID("America/Montreal");

		DateTimeFormatter formatter = DateTimeFormat.forPattern(
				"MM/dd/yyyy HH:mm").withZone(timeZone);

		DateTime dateTimeStart = formatter.parseDateTime(currentDate);
		DateTime dateTimeStop = formatter.parseDateTime(salesStartDate);
		Period period = new Period(dateTimeStart, dateTimeStop);
		PeriodFormatter periodFormatter = PeriodFormat.getDefault();
		String output = periodFormatter.print(period);

		// getremainingsalestime(output,finishtimemain);

		String splitdatetime[] = output.split("and");

		for (int i = 0; i < splitdatetime.length; i++)
			splitdatetime[i] = splitdatetime[i].trim();

		String result = "", tagvalue = "";

		for (int i = 0; i < splitdatetime.length; i++) {
			String datetime = splitdatetime[i];
			String[] timePosNegativesplit = datetime.split(",");
			String timePosNegative = timePosNegativesplit[0];
			String[] diftime = timePosNegative.split(" ");
			String dtime = diftime[0];

			String tag = diftime[1];
			if ((tag.equals("day")) && (Integer.parseInt(dtime) > 0)) {

				result = dtime;
				break;

			}

		}
		return result;

	}*/

}
